package com.hrp.config;

import com.hrp.domain.Menus;
import com.hrp.domain.Role;
import com.hrp.domain.User;
import com.hrp.hrpdao.MenusDao;
import com.hrp.hrpdao.RoleDao;
import com.hrp.hrpdao.UserDao;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/8/4 0004.
 */
public class AuthRealm extends AuthorizingRealm {

    private static final Logger log = LoggerFactory.getLogger(AuthRealm.class);

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private MenusDao menusDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        User user=(User) principal.fromRealm(this.getClass().getName()).iterator().next();//获取session中的用户
        List<String> permissions=new ArrayList<>();
        List<Role> roles = user.getRoleList();
        if(roles.size()>0) {
            for(Role role : roles) {
                List<Menus> menus = role.getMenusList();
                if(menus.size()>0) {
                    for(Menus menu : menus) {
                        if(menu.getMenuUrl()==null || menu.getMenuUrl().equals("")){

                        }else {
                            permissions.add(menu.getMenuUrl());
                        }

                    }
                }
            }
        }
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addStringPermissions(permissions);//将权限放入shiro中.
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken utoken=(UsernamePasswordToken) token;//获取用户输入的token
        String username = utoken.getUsername();
        User user = userDao.findUserByUserName(username);
        if(user==null){
            log.info("当前用户不存在");
            throw new UnknownAccountException();
        }
        List<Role> roleList = roleDao.findRoleListByUserId(user.getId());
        for(Role role : roleList){
            List<Menus> menusList = menusDao.findMenusListByRoleId(role.getId());
            role.setMenusList(menusList);
        }
        user.setRoleList(roleList);

        return new SimpleAuthenticationInfo(user, user.getPassword(),this.getClass().getName());//放入shiro.调用CredentialsMatcher检验密码
    }
}
